#include "reg52.h"

unsigned char  code SMG[18] =	{0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90,0x88,0x80,0xc6,0xc0,0x86,0x8e,0xbf,0x7f};

sfr P4 = 0xc0;

sbit R1 = P3^0;
sbit R2 = P3^1;
sbit R3 = P3^2;
sbit R4 = P3^3;

sbit B1 = P4^4;
sbit B2 = P4^2;
sbit B3 = P3^5;
sbit B4 = P3^4;


void Slect573(unsigned char n)
{
	switch(n)
	{
		case 4:
			P2 = (P2 & 0x1f) | 0x80;
			break;
		case 5:
			P2 = (P2 & 0x1f) | 0xa0;
			break;
		case 6:
			P2 = (P2 & 0x1f) | 0xc0;
			break;
		case 7:
			P2 = (P2 & 0x1f) | 0xe0;	
			break;
	}
}

unsigned char Key_num = 0;

void DisplayLED(unsigned char i)
{
	Slect573(6);
	P0 = 0x01;
	Slect573(7);
	P0 = i;
}

void ScanKey()
{
	R1 = 0;
	R4 = R2 = R3 = 1;
	B1 = B2 = B3 = B4 =1;
	if(B1 == 0)
	{
		while(B1 == 0);
		Key_num = 0;
		DisplayLED(SMG[Key_num]);
	}
	
	else if(B2 == 0)
	{
		while(B2 == 0);
		Key_num = 1;
		DisplayLED(SMG[Key_num]);
	}
	
	else if(B3 == 0)
	{
		while(B3 == 0);
		Key_num = 2;
		DisplayLED(SMG[Key_num]);
	}	
	
	else if(B4 == 0)
	{
		while(B4 == 0);
		Key_num = 3;
		DisplayLED(SMG[Key_num]);
	}
	
	R2 = 0;
	R1 = R4 = R3 = 1;
	B1 = B2 = B3 = B4 =1;
	if(B1 == 0)
	{
		while(B1 == 0);
		Key_num = 4;
		DisplayLED(SMG[Key_num]);
	}
	
	else if(B2 == 0)
	{
		while(B2 == 0);
		Key_num = 5;
		DisplayLED(SMG[Key_num]);
	}
	
	else if(B3 == 0)
	{
		while(B3 == 0);
		Key_num = 6;
		DisplayLED(SMG[Key_num]);
	}	
	
	else if(B4 == 0)
	{
		while(B4 == 0);
		Key_num = 7;
		DisplayLED(SMG[Key_num]);
	}

	R3 = 0;
	R1 = R2 = R4 = 1;
	B1 = B2 = B3 = B4 =1;	
	if(B1 == 0)
	{
		while(B1 == 0);
		Key_num = 8;
		DisplayLED(SMG[Key_num]);
	}
	
	else if(B2 == 0)
	{
		while(B2 == 0);
		Key_num = 9;
		DisplayLED(SMG[Key_num]);
	}
	
	else if(B3 == 0)
	{
		while(B3 == 0);
		Key_num = 10;
		DisplayLED(SMG[Key_num]);
	}	
	
	else if(B4 == 0)
	{
		while(B4 == 0);
		Key_num = 11;
		DisplayLED(SMG[Key_num]);
	}	

	R4 = 0;
	R1 = R2 = R3 = 1;
	B1 = B2 = B3 = B4 =1;	
	if(B1 == 0)
	{
		while(B1 == 0);
		Key_num = 12;
		DisplayLED(SMG[Key_num]);
	}
	
	else if(B2 == 0)
	{
		while(B2 == 0);
		Key_num = 13;
		DisplayLED(SMG[Key_num]);
	}
	
	else if(B3 == 0)
	{
		while(B3 == 0);
		Key_num = 14;
		DisplayLED(SMG[Key_num]);
	}	
	
	else if(B4 == 0)
	{
		while(B4 == 0);
		Key_num = 15;
		DisplayLED(SMG[Key_num]);
	}	
}

void main()
{
	while(1)
	{
		ScanKey();
	}
}	
